package com.reach.redis.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.reach.redis.bean.CacheBean;
import com.reach.redis.bo.CacheConfig;
import com.reach.redis.interceptor.CacheInterceptor;
import com.reach.redis.proxy.CGLIBProxy;

public class ManagerCache {
	
	public static final Map<String,CacheConfig> queryCacheMap = new ConcurrentHashMap<>();	
	
	public static volatile boolean   enableCache = false;
	
	public void  add(CacheConfig cacheConfig) {
		queryCacheMap.put(getCacheKey(cacheConfig), cacheConfig);
	} 
	
	public void initProxy(CacheConfig cacheConfig) {
		if(queryCacheMap.containsKey(getCacheKey(cacheConfig))) {
			return;
		}
		add(cacheConfig);
		/*BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
		beanNameAutoProxyCreator.setInterceptorNames("cacheInterceptor");
		beanNameAutoProxyCreator.setBeanNames("baiduGeocoderService");
		SpringContextUtil.registerBean("beanNameAutoProxyCreator",beanNameAutoProxyCreator.getClass());*/
		
		Object obj =	CGLIBProxy.createProxy(cacheConfig.getTargetObject(),new CacheInterceptor());
		CacheBean.add(cacheConfig.getBeanName(),obj);
		SpringContextUtil.unregisterBean("baiduGeocoderService");
		SpringContextUtil.registerBean("baiduGeocoderService",obj.getClass());
		/*BeanNameAutoProxyCreator beanNameAutoProxyCreator =  (BeanNameAutoProxyCreator) SpringContextUtil.getBean("beanNameAutoProxyCreator");
		beanNameAutoProxyCreator.setBeanNames("baiduGeocoderService");
		beanNameAutoProxyCreator.setInterceptorNames("cacheInterceptor");*/
		
		
	}

	private String getCacheKey(CacheConfig cacheConfig){
		StringBuilder sb = new StringBuilder();
		sb.append(cacheConfig.getTargetObject().getClass().getName());
		sb.append(".");
		sb.append(cacheConfig.getTargetMethod().getName());
		return String.valueOf(sb);
	}
	
	
	private String[] getBeanNames() {
		List<String> beanList = new ArrayList();
		for(Map.Entry<String, CacheConfig>  cache : queryCacheMap.entrySet()) {
			beanList.add(cache.getValue().getBeanName());
		}
		return null;
	}
}
